//
//  ZRAccountManager.m
//  简书:https://www.jianshu.com/u/043e94ca450f
//
//  Created by 黄涛 on 2018/8/6.
//  Copyright © 2018年 zero. All rights reserved.
//  

#import "ZRAccountManager.h"
#import <SVProgressHUD/SVProgressHUD.h>
static ZRAccountManager * _manager;

@implementation ZRAccountManager

+ (instancetype)sharedManager{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _manager = [[ZRAccountManager alloc] init];
        
    });
    
    return _manager;
    
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _manager = [super allocWithZone:zone];
    });
    
    return _manager;
}

#pragma mark - 校验账号密码
+ (BOOL)checkAccount:(NSString *)account password:(NSString *)password verificationCode:(NSString *)verificationCode isLogin:(BOOL)isLogin{
    
    if (account.length <= 0 || password.length <= 0 ) {
        
         [SVProgressHUD showErrorWithStatus:@"请输入账号/密码"];
         return NO;
    }
    
    //手机号登录，验证手机号合法性
    if (!account.zr_isPhoneNum) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return NO;
    }
    [[NSUserDefaults standardUserDefaults] setObject:account forKey:ZRLastAccountKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //验证密码合法性
    if (![password zr_checkPasswordMin:6 max:16]) {
        
        [SVProgressHUD showErrorWithStatus:(isLogin ? @"账号/密码错误" : @"密码必须是6-20位字母+数字组合，不包含特殊字符哦~")];
        return NO;
    }
    
    //验证 验证码 是否存在，合法性
    if (verificationCode.hash && (verificationCode.zr_isNumber || verificationCode.length != 6)) {
        
        [SVProgressHUD showInfoWithStatus:@"验证码输入有误"];
        return NO;
    }
    
    return YES;
}


#pragma mark - 登录
/** 账号密码登录 */
+ (void)loginWithAccount:(NSString *)account password:(NSString *)password  complete:(void(^)(BOOL isSuccess , NSInteger errorCode))complete{
    
    if ([self checkAccount:account password:password verificationCode:nil isLogin:YES]){
        
        [SVProgressHUD showWithStatus:@"正在登录"];
        [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeClear)];
        
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        params[@"account"] = account;
        params[@"password"] = password;
        
        
        [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"login" parameters:params finishedBlock:^(id responseObj, NSError *error) {
            
            [SVProgressHUD dismiss];
            
            NSInteger errorCode = [responseObj[@"errorCode"] integerValue];
            
            if (error) {
                !complete ? : complete(NO,errorCode);
            }
            
            BOOL success = errorCode == 0 ? YES : NO;
            
            !complete ? : complete(success,errorCode);
            
            [[NSUserDefaults standardUserDefaults] setObject:account forKey:ZRLastAccountKey];
            [[NSUserDefaults standardUserDefaults] setObject:account forKey:ZRCurrentAccountKey];
            [[NSUserDefaults standardUserDefaults] setObject:responseObj[@"data"][@"uid"] forKey:ZRCurrentUidKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }];
        
    }

       
}

#pragma mark - 注销
+ (void)logout:(void(^)(BOOL isSuccess))complete{
    
    
    //数据操作
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:ZRCurrentUidKey];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:ZRCurrentAccountKey];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    !complete ? : complete(YES);
    
    [SVProgressHUD showSuccessWithStatus:@"账号已注销"];

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}


#pragma mark - 注册
+ (void)registerWithAccount:(NSString *)account password:(NSString *)password verificationCode:(NSString *)verificationCode otherParam:(NSDictionary *)otherParam complete:(void(^)(BOOL isSuccess))complete{
    
    if ([self checkAccount:account password:password verificationCode:verificationCode isLogin:NO]) {
        
        [SVProgressHUD showWithStatus:@"正在加载"];
        [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeClear)];
        
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        params[@"account"] = account;
        params[@"password"] = password;
        params[@"sms_code"] = verificationCode;
        
        if(otherParam) [params addEntriesFromDictionary:otherParam];
        
        [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"regist" parameters:params finishedBlock:^(id responseObj, NSError *error) {
            
            [SVProgressHUD dismiss];
            
            if (error) {
                !complete ? : complete(NO);
                return ;
            }
            
            !complete ? : complete(YES);
            
            [[NSUserDefaults standardUserDefaults] setObject:account forKey:ZRLastAccountKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }];
    }

}

#pragma mark - 验证码请求
+ (void)verificationCodeRequestWithPhoneNum:(NSString *)phoneNum complete:(void(^)(BOOL isSuccess , NSString * btnTitle))complete{
    
    if (!phoneNum.zr_isPhoneNum) {
        
        [SVProgressHUD showInfoWithStatus:@"请输入正确手机号"];
        !complete ? :complete(NO,@"发送验证码");
        return;
    }
    
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"phone"] = phoneNum;

    [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"User/sendSms" parameters:params finishedBlock:^(id responseObj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error) {
            !complete ? : complete(NO,@"发送验证码");
            return ;
        }
        
        !complete ? : complete(YES, @"");
        [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
        
    }];
    
}

#pragma mark - 重置密码
+ (void)resetPasswordWithAccount:(NSString *)account password:(NSString *)password verificationCode:(NSString *)verificationCode complete:(void(^)(BOOL isSuccess))complete{
    
    if ([self checkAccount:account password:password verificationCode:verificationCode isLogin:NO]) {
        
        [SVProgressHUD showWithStatus:@"正在加载"];
        [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeClear)];
        
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        params[@"account"] = account;
        params[@"password"] = password;
        params[@"sms_code"] = verificationCode;
        
        [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"reset" parameters:params finishedBlock:^(id responseObj, NSError *error) {
            
            [SVProgressHUD dismiss];
            
            if (error) {
                !complete ? : complete(NO);
                return ;
            }
            
            !complete ? : complete(YES);
            
            [[NSUserDefaults standardUserDefaults] setObject:account forKey:ZRLastAccountKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }];
    }
    
}


#pragma mark - 个人信息
/** 获取个人信息 */
+ (void)getUserInfo:(void(^)(BOOL isSuccess , id responseObj))complete{
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    
    [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"getUserInfo" parameters:params finishedBlock:^(id responseObj, NSError *error) {
  
       !complete ? : error ?  complete(NO,nil) : complete(YES,responseObj);
    
    }];

}

/** 修改个人信息 */
+ (void)changeUserInfo:(NSDictionary *)userInfo complete:(void(^)(BOOL isSuccess))complete{
    
    [SVProgressHUD showWithStatus:@"正在加载"];
    [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeClear)];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    if(userInfo) [params addEntriesFromDictionary:userInfo];

    [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"change" parameters:params finishedBlock:^(id responseObj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error) {
            [SVProgressHUD showInfoWithStatus:@"修改失败 请重试"];
            !complete ? : complete(NO);
            return ;
        }
        
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        !complete ? : complete(YES);
    }];
}


#pragma mark - 上传头像
+ (void)uploadIcon:(UIImage *)icon complete:(void(^)(BOOL isSuccess , id responseObj))complete{
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"] = @"";
    
    [[ZRNetworkingTool shareTool] uploadFilesWithUrl:@"icon" parameters:params fileName:@"files" filesPath:@[icon] progress:nil finishedBlock:^(id responseObj, NSError * error) {
      
        [SVProgressHUD showInfoWithStatus:(error ? @"上传失败":@"上传成功")];
        !complete ? : error ? complete(NO,nil) : complete(YES,responseObj);
        
    }];
   
}


@end
